#1,导入motor和asyncio库
import motor.motor_asyncio,asyncio
#2，建立服务连接
client = motor.motor_asyncio.AsyncIOMotorClient('127.0.0.1', 27017)
#3，切换到指定的数据库和集合，也可以使用col= client.testdb. fruitshop这种风格
db = client['testdb']
col = db['fruitshop']
#4，定义一组协程函数，实现插入协程/更新/查询
async def do_insert():
    item = {"name": "apple", "tags": "red", "qty": 10}
    result = await col.insert_one(item)
    print('acknowledged: %s, inserted ID: %s' %(result.acknowledged,result.inserted_id))
async def do_update():
    result = await col.update_one({"name": "apple"}, {'$set': {'qty': 9}})
    print('updated %s document' % result.modified_count)
async def do_find():
    cursor = col.find({"records.num": {'$lt': 11}}).sort("records.num")
    for document in await cursor.to_list(length=100):
        print(document)
#5,执行一组异步任务
tasks = [do_insert(),do_update(),do_find()]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
db.client.close()
